﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Rw.Core.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WH.Common.CustomException;

namespace WH.Common.Filter
{
    /// <summary>
    /// 全局异常错误日志
    /// </summary>
    public class GlobalExceptionsFilter : IExceptionFilter
    {
        private readonly IHostEnvironment _env;
        private readonly ILogger<GlobalExceptionsFilter> _loggerHelper;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="env"></param>
        /// <param name="loggerHelper"></param>
        public GlobalExceptionsFilter(IHostEnvironment env, ILogger<GlobalExceptionsFilter> loggerHelper)
        {
            _env = env;
            _loggerHelper = loggerHelper;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="context"></param>
        public void OnException(ExceptionContext context)
        {

            var exception = context.Exception;

            var response = new ResultResponse();

            var result = new JsonResult(null);


            if (context.Exception is BadRequestException)
            {
                response.Code = 400;
                response.IsSucceed = false;
                response.Msg = context.Exception.Message;

                context.HttpContext.Response.StatusCode = 400;
            }
            else if (context.Exception is NotImplementedException)
            {
                response.Code = 200;
                response.IsSucceed = true;
                response.Msg = "功能暂未对接";

                context.HttpContext.Response.StatusCode = 200;
            }
            else
            {
                response.Code = 500;
                response.IsSucceed = false;
                response.Msg = context.Exception.Message;

                context.HttpContext.Response.StatusCode = 500;
            }

            result.Value = response;

            context.Result = result;
            context.ExceptionHandled = true;

            var errStr = $"\r\n" +
                $"【错误消息】：{exception.Message} \r\n" +
                $"【异常类型】：{exception.GetType().Name} \r\n" +
                $"【异常信息】：{exception.Message} \r\n" +
                $"【堆栈调用】：{exception.StackTrace}";

            //采用log4net 进行错误日志记录
            _loggerHelper.LogError(errStr);
        }

        /// <summary>
        /// 自定义返回格式
        /// </summary>
        /// <param name="throwMsg"></param>
        /// <param name="ex"></param>
        /// <returns></returns>
        public string WriteLog(string throwMsg, Exception ex)
        {
            return string.Format("【自定义错误】：{0} \r\n【异常类型】：{1} \r\n【异常信息】：{2} \r\n", new object[] { throwMsg,
                ex.GetType().Name, JsonConvert.SerializeObject(ex) });
        }

    }

    /// <summary>
    /// 
    /// </summary>
    public class InternalServerErrorObjectResult : ObjectResult
    {
        /// <summary>
        /// 
        /// </summary>
        public InternalServerErrorObjectResult(object value) : base(value)
        {
            StatusCode = StatusCodes.Status500InternalServerError;
        }
    }
    /// <summary>
    /// 返回错误信息
    /// </summary>
    public class JsonErrorResponse
    {
        /// <summary>
        /// 生产环境的消息
        /// </summary>
        public string? Message { get; set; }
        /// <summary>
        /// 开发环境的消息
        /// </summary>
        public string? DevelopmentMessage { get; set; }
    }

}
